package jgcp.utils;
/**
 * 
 * @Date 31/05/2009
 * @author Jie Zhao (288654)
 * @version 1.0
 */
public class ByteUtil {
	private ByteUtil() {
	}

	/**
	 * parse a byte array to an integer
	 * 
	 * @param b
	 * @param start
	 * @return
	 */
	public static int parseInt(byte[] b, int start) {
		if (b == null || b.length < start + (Integer.SIZE / Byte.SIZE))
			return 0;
		else {
			int result = 0;
			int size = Integer.SIZE / Byte.SIZE;
			for (int i = 0; i < size; i++) {
				result += (0xff << ((size - i - 1) * Byte.SIZE))
						& (b[i + start] << ((size - i - 1) * Byte.SIZE));
			}
			return result;
		}
	}

	/**
	 * fill a byte array with a integer
	 * 
	 * @param b
	 * @param start
	 * @param number
	 */
	public static void fillByInt(byte[] b, int start, int number) {
		if (b == null || start + (Integer.SIZE / Byte.SIZE) > b.length)
			return;
		for (int i = 0; i < (Integer.SIZE / Byte.SIZE); i++) {
			// System.out.println(((Integer.SIZE/Byte.SIZE -i-1)*Byte.SIZE));
			b[i + start] = (byte) (number >> ((Integer.SIZE / Byte.SIZE - i - 1) * Byte.SIZE));
		}
	}

	/**
	 * print a byte array in form of Hex string
	 * 
	 * @param b
	 */
	public static void printByteArray(byte[] b) {
		int count = 0;
		for (byte bb : b) {
			System.out.print(Integer.toHexString(bb));
			if (++count < b.length)
				System.out.print(":");
		}
		System.out.println();
	}
}
